import UrlUtil from './url';

/**
 * 对Url的一些处理方法
 */
export const Url = UrlUtil;

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function dateFormat(date, format = 'yyyy-MM-dd hh:mm:ss') {
    if (arguments.length === 0 || !date) {
        // date = new Date();
        return '';
    }
    let newDate;
    let weekArray = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
    if (typeof date === 'object') {
        newDate = date;
    } else {
        if (typeof date === 'string' && /^[0-9]+$/.test(date)) {
            date = parseInt(date);
        } else if (typeof date === 'number' && date.toString().length === 10) {
            date = date * 1000;
        } else if (typeof date === 'string' && /^\d{4}-\d{1,2}-\d{1,2}/.test(date)) {
            date = date.replace(/-/g, '/');
        }
        newDate = new Date(date);
    }
    let dateObj = {
        'M+': newDate.getMonth() + 1,
        'd+': newDate.getDate(),
        'h+': newDate.getHours(),
        'm+': newDate.getMinutes(),
        's+': newDate.getSeconds(),
        'q+': Math.floor((newDate.getMonth() + 3) / 3),
        'S+': newDate.getMilliseconds(),
        'w+': newDate.getDay(),
        'W+': weekArray[newDate.getDay()],
    };

    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (newDate.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (let k in dateObj) {
        if (new RegExp('(' + k + ')').test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? dateObj[k] : ('00' + dateObj[k]).substr(('' + dateObj[k]).length));
        }
    }
    return format;
}

/**
 * 多少分钟前，多少天前
 * @param {int} timestamp
 */
export function dateDiff(timestamp) {
    // 补全为13位
    var arrTimestamp = (timestamp + '').split('');
    for (var start = 0; start < 13; start++) {
        if (!arrTimestamp[start]) {
            arrTimestamp[start] = '0';
        }
    }
    timestamp = arrTimestamp.join('') * 1;

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
        return '不久前';
    }

    // 计算差异时间的量级
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    // 数值补0方法
    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    // 使用
    if (monthC > 12) {
        // 超过1年，直接显示年月日
        return (function () {
            var date = new Date(timestamp);
            return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
        })();
    } else if (monthC >= 1) {
        return parseInt(monthC) + '月前';
    } else if (weekC >= 1) {
        return parseInt(weekC) + '周前';
    } else if (dayC >= 1) {
        return parseInt(dayC) + '天前';
    } else if (hourC >= 1) {
        return parseInt(hourC) + '小时前';
    } else if (minC >= 1) {
        return parseInt(minC) + '分钟前';
    }
    return '刚刚';
}

/**
 * @desc    价格过滤器
 * @param   {[Number|String]}   arg      原始参数
 * @param   {[Number]}          num      小数点位
 * @param   {[String]}          symbol   符号
 * @param   {[Boolean]}         spilt    是否进行逗号分隔
 * @return  {[String]}
 * price | priceFormat(2, '￥', true)
 */
export const priceFormat = (arg = '0', num = 2, symbol, spilt = false) => {
    arg = arg
        ? Number(arg)
              .toFixed(num)
              .replace(/[.]?0+$/, '')
        : '0';
    if (spilt == true) {
        if (arg.indexOf('.') == -1) {
            arg = arg.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        } else {
            let parts = arg.split('.');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            arg = parts.join('.');
        }
    }

    if (symbol) {
        arg = symbol + arg;
    }
    return arg;
};

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
    // returns the byte length of an utf8 string
    let s = str.length;
    for (var i = str.length - 1; i >= 0; i--) {
        const code = str.charCodeAt(i);
        if (code > 0x7f && code <= 0x7ff) s++;
        else if (code > 0x7ff && code <= 0xffff) s += 2;
        if (code >= 0xdc00 && code <= 0xdfff) i--;
    }
    return s;
}

/**
 * @param {string} val
 * @param {number} maxLength
 * @returns {string}
 */
export function html2Text(val = '', maxLength = 0) {
    const div = document.createElement('div');
    div.innerHTML = val;
    let text = div.textContent || div.innerText;
    return maxLength > 0 ? text.substring(0, maxLength) : text;
}

/**
 * @param {string} str
 * @returns {string}
 */
export function return2Br(str) {
    return str.replace(/[\n↵]/g, '<br/>');
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
    if (typeof target !== 'object') {
        target = {};
    }
    if (Array.isArray(source)) {
        return source.slice();
    }
    Object.keys(source).forEach((property) => {
        const sourceProperty = source[property];
        if (typeof sourceProperty === 'object') {
            target[property] = objectMerge(target[property], sourceProperty);
        } else {
            target[property] = sourceProperty;
        }
    });
    return target;
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone');
    }
    const targetObj = source.constructor === Array ? [] : {};
    Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys]);
        } else {
            targetObj[keys] = source[keys];
        }
    });
    return targetObj;
}

/**
 * 格式化文件大小
 * @param {*} value Bytes
 */
export function renderSize(value) {
    if (null == value || value == '') {
        return '0 Bytes';
    }
    let unitArr = new Array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    let index = 0;
    let srcsize = parseFloat(value);
    index = Math.floor(Math.log(srcsize) / Math.log(1024));
    let size = srcsize / Math.pow(1024, index);
    size = size.toFixed(2); //保留的小数位数
    return size + unitArr[index];
}

// 生成GUID（全局唯一标识符）
export function guid() {
    return Math.random().toString().substr(3, 8) + Date.now();
}

// 手机号码隐藏
export function phoneNumHide(phone) {
    if (phone) {
        let phoneNew = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
        return phoneNew;
    } else {
        return '';
    }
}
